<script lang="ts" setup>
import { useRouter } from 'vue-router'
import { onMounted, ref } from 'vue'
import { mobileRules, codeRules } from '@/utils/rules'
import login from './composable/login'
import type { BindForm } from '@/types/user'
import { useUserStore } from '@/stores'

const router = useRouter()
const { returnUrl, setReturnUrl } = useUserStore()

const isNeedBind = ref(false)
const openId = ref('')

const routerCallback = () => {
  router.replace({
    path: returnUrl || '/user'
  })
  setReturnUrl()
}

const otherCallback = (id: string) => {
  isNeedBind.value = true
  openId.value = id
}

const { loginFormRef, mobile, code, time, getCode, onUserLogin } = login(
  routerCallback,
  otherCallback
)

const onBindUserQQAndMobile = async (form: Omit<BindForm, 'openId'>) => {
  const bindForm = {
    ...form,
    openId: openId.value
  }
  onUserLogin('bindUser', bindForm)
}

const isNeedBindDetermine = () => {
  const isLogin = window.QC.Login.check()
  if (isLogin) {
    window.QC.Login.getMe((id) => {
      onUserLogin('qqLogin', id)
    })
  } else {
    router.replace('/login')
  }
}

onMounted(() => {
  isNeedBindDetermine()
})
</script>

<template>
  <div class="login-page" v-if="isNeedBind">
    <cp-nav-bar></cp-nav-bar>
    <div class="login-head">
      <h3>手机绑定</h3>
    </div>
    <van-form
      autocomplete="off"
      ref="loginFormRef"
      @submit="onBindUserQQAndMobile"
    >
      <van-field
        v-model="mobile"
        :rules="mobileRules"
        name="mobile"
        placeholder="请输入手机号"
      ></van-field>
      <van-field
        v-model="code"
        :rules="codeRules"
        name="code"
        placeholder="请输入验证码"
      >
        <template #button>
          <span class="btn-send" :class="{ active: !time }" @click="getCode">{{
            time ? `${time}s后再次发送` : '发送验证码'
          }}</span>
        </template>
      </van-field>
      <div class="cp-cell">
        <van-button
          style="margin-top: 50px"
          block
          round
          type="primary"
          native-type="submit"
        >
          立即绑定
        </van-button>
      </div>
    </van-form>
  </div>
</template>

<style lang="scss" scoped>
@import '@/styles/login.scss';
</style>
